package cc.ilzy.mall.model.vo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@ApiModel(value = "购物车", description = "购物车")
@Data
@Accessors(chain = true)
public class CartVO implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;
    @ApiModelProperty("购物项")
    private List<CartItemVO> cartItems;

    @ApiModelProperty("购物车中商品数量")
    private Integer totalNum;

    @ApiModelProperty("购物车中总金额")
    private BigDecimal totalAmount;

    @ApiModelProperty("购物车中应支付总金额")
    private BigDecimal realPayAmount;

    /**
     * 获取购物车数量
     *
     * @return
     */
    public Integer getTotalNum() {
        List<CartItemVO> list = Optional.ofNullable(this.cartItems).orElse(Collections.emptyList());
        if (list.isEmpty()) {
            return 0;
        }
        return list.stream().mapToInt(CartItemVO::getBuyNum).sum();
    }


    /**
     * 获取购物车总金额
     *
     * @return
     */
    public BigDecimal getTotalAmount() {
        BigDecimal totalAmount = BigDecimal.ZERO;
        if (this.cartItems != null) {
            return this.cartItems.stream()
                                 .reduce(totalAmount, (subtotal, item) -> subtotal.add(item.getTotalAmount()),
                                         BigDecimal::add);
        }
        return totalAmount;
    }


    /**
     * 获取购物车实际支付金额
     * @return
     */
    public BigDecimal getRealPayAmount() {
        BigDecimal totalAmount = BigDecimal.ZERO;
        if (this.cartItems != null) {
            return this.cartItems.stream()
                                 .reduce(totalAmount, (subtotal, item) -> subtotal.add(item.getTotalAmount()),
                                         BigDecimal::add);
        }
        return totalAmount;
    }
}
